/*留言管理页面*/
import React, { Fragment, useEffect, useState } from 'react';
import moment from 'moment';
import ipPort from '../../../common/ipPort'
import {
  Row,
  Col,
  Form,
  Input,
  Button,
  Table,
  Popconfirm,
  Divider,
  Spin,
  Space,
  Tag,
  Select,
  message,
} from 'antd';
import Style from './style.module.scss';
import MessageComponent from './MessageComponent';
import { get } from '../../../utils/requestUtil';
import { getUserInfo } from '../../../utils/Info';

function Index(props) {    
    const [visible, setVisible] = useState(false)
    const [loading, setLoading] = useState(false)
    const [keyword, setKeyword] = useState('')
    const [state, setState] = useState(0) // 状态 0 是未处理，1 是已处理 ,'' 代表所有留言
    const [pageNum, setPageNum] = useState(1)
    const [pageSize, setPageSize] = useState(10)
    const [messageList, setMessageList] = useState([])
    const [messageDetail, setMessageDetail] = useState({})
    const { userId, account } = getUserInfo()

    const columns = [
        {
          title: '用户名',
          dataIndex: 'username',
        },
        {
          title: '文章',
          dataIndex: 'title',
          render: (text, record) => (
          <Space size="middle">
            <a href={`https://blog.ztime.tech/detail?id=${record['articleId']}&author=${account}`}>{text}</a>
          </Space>)
        },
        
        {
          title: '邮箱',
          dataIndex: 'email',
        },
        {
          title: '手机',
          dataIndex: 'phone',
        },
        // {
        // 	title: '用户介绍',
        // 	dataIndex: 'introduce',
        // },
        {
          title: '内容',
          width: 300,
          dataIndex: 'content',
        },
        {
          title: '状态',
          dataIndex: 'state',
          render: val => (val === '1' ? <Tag color="green">已经处理</Tag> : <Tag color="red">未处理</Tag>),
        },
        {
          title: '创建时间',
          dataIndex: 'create_time',
          sorter: true,
          render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
        },
        {
          title: '操作',
          width: 150,
          render: (text, record) => (
            <Space>
              <Button type={'primary'} onClick={() => showReplyModal(record)}>回复</Button>             
              <Popconfirm title="确认删除?" onConfirm={() => handleDelete(text, record)}>
                <Button type={'primary'}>删除</Button>
              </Popconfirm>
            </Space>
          ),
        },
    ];
    
    const pagination = {
        defaultCurrent: 1,
        pageSize,
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => {
            handleChangePageParam(current, pageSize);
        },
        onChange: (current, pageSize) => {
            handleChangePageParam(current, pageSize);
        },
    }

    useEffect(()=> {
        handleSearch();
    }, [])

    function handleChangeState(state) {
        setState(state)
        handleSearch();      
    }

    function handleChangeKeyword(event) {
        setKeyword(event.target.value)
    }

    function handleChangePageParam(pageNum, pageSize) {
        setPageNum(pageNum)
        setPageSize(pageSize)
        handleSearch()
    }

    const showReplyModal = (record) => {
      setVisible(true)
      setMessageDetail(record)
    };

    const handleOk = () => {
        setVisible(false)  
    };

    const handleCancel = e => {
      setVisible(false)
    };

    const handleSearch = async (keyword, state) => {
      setLoading(true)
      try {
       
        let res = await get(ipPort+'/default/getComments', { userId, keyword, state, pageNum, pageSize })
        if (res.success) {
          setLoading(false)
          setMessageList(res.comments)
        }
      } catch (e) {
        setLoading(false)
        message.error(`获取文章评论失败,异常信息：${e}`)
      }
    };

    const handleDelete = async (text, record) => {
      setLoading(true)
      try {
        let userId = getUserInfo().userId
        let res = await get('/default/deleteComment', { userId, commentId: record.Id, keyword, pageNum, pageSize })
        if (res.success) {
          setLoading(false)
          setMessageList(res.comments)
          message.error(`删除文章评论成功`)
        }
      } catch (e) {
        setLoading(false)
        message.error(`删除文章评论失败,异常信息：${e}`)
      }
    };

    const query = (values) => {
      let {keyword, state } =values
      handleSearch(keyword, state)
    }

    const renderSimpleForm = () => {
        return (
        <Form layout={'vertical'} name="controrl-ref" onFinish={query}>
          <Row align={'middle'} gutter={30}>
            <Col span={8}>
                <Form.Item name="keyword" label="留言内容">
                <Input
                  placeholder="留言内容"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="state" label="状态">
                <Select
                style={{ width: 200, marginRight: 20 }}
                placeholder="选择状态"
                >
                  <Select.Option value="">所有</Select.Option>
                  <Select.Option value="0">未处理</Select.Option>
                  <Select.Option value="1">已处理</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8} style={{textAlign: 'left'}}>
                <Button type={'primary'} htmlType={'search'}>
                  查询
                </Button>
            </Col>
          </Row>
        </Form>
      );
    }

    return (
      <div className={Style.container}>
        <div className="">{renderSimpleForm()}</div>
        <Spin spinning={loading}>
            <Table
            pagination={pagination}
            rowKey={record => record._id}
            columns={columns}
            bordered
            dataSource={messageList}
            />
        </Spin>
      
        <MessageComponent
          messageDetail={messageDetail}
          visible={visible}
          setMessageList={setMessageList}
          handleOk={handleOk}
          handleCancel={handleCancel}
        />
      </div>
    )
}

export default Index
